<template>
  <div>
    <div class="pt-18 pb-20 mx-auto">
      <a-descriptions class="mb-4" size="middle" bordered :column="1">
        <a-descriptions-item label="起始行">
          <a-input-number
            id="inputNumber"
            v-model:value="startRow"
            :min="1"
            :max="10"
            @change="handleStartRowChange"
          />
        </a-descriptions-item>
      </a-descriptions>

      <a-table
        v-if="columns && columns.length"
        size="middle"
        :columns="columns"
        :data-source="dataSource"
        :pagination="false"
        :scroll="{ x: '100%', y: 100 }"
      >
        <template #headerCell="{ column }">
          <div :class="[column.require ? 'require-mark' : '']">{{ column.title }}</div>
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'importField'">
            {{ record[column.dataIndex] }}
          </template>
          <template v-if="column.dataIndex !== 'importField'">
            <a-select
              show-search
              option-filter-prop="label"
              :options="columnOptions"
              v-model:value="record[column.dataIndex]"
              style="width: 100%"
            >
            </a-select>
          </template>
        </template>
      </a-table>

      <div class="import-config-tips">
        <p>1、如使用自定义导入模板，需正确关联模板字段与导入字段</p>
        <p>2、默认读取第一个工作表（Sheet）</p>
        <p>3、系统将从“起始行”开始读取Excel数据并作为“导入字段”</p>
        <p>4、<span class="require-mark">表示此项为必填项</span></p>
      </div>
    </div>

    <div class="footer-button">
      <a-button type="primary" @click="handleStepNext" :loading="nextBtnLoading">
        <template #icon>
          <Icon icon="ant-design:right-outlined" />
        </template>
        下一步
      </a-button>
    </div>
  </div>
</template>

<script lang="ts">
  import { computed, defineComponent, ref, watch } from 'vue';
  import { Icon } from '@/components/Icon';
  import { SysImportExcelTemplate } from '@/api/sys/model/sysImportExcelTemplateModel';
  import { message, Select } from 'ant-design-vue';
  import { FileInfo } from '@/api/file/model/fileInfoModel';
  import type { BasicColumn } from '@/components/Table';
  import { analysis, analysisExcel } from '@/api/sys/sysImportExcelData';
  import { SysImportExcelTemplateDetailVO } from '@/api/sys/model/sysImportExcelTemplateDetailModel';

  export default defineComponent({
    components: { Select, Icon },
    props: {
      sysImportExcelTemplate: {
        type: Object as PropType<SysImportExcelTemplate>,
      },
      importFile: {
        type: Object as PropType<FileInfo>,
      },
    },
    emits: ['next'],
    setup(props, { emit }) {
      const nextBtnLoading = ref<boolean>(false);

      // 系统预设导入模版
      const columns = ref<Array<any>>([]);
      // 导入字段
      const dataSource = ref<Array<BasicColumn>>([]);
      // 用户导入Excel前10条数据
      const importExcelColumns = ref<Array<Array<string>>>([]);
      // 起始行
      const startRow = ref(2);

      watch(
        () => [props.sysImportExcelTemplate, props.importFile],
        () => initConfig(),
      );

      initConfig();

      /**
       * 初始化配置导入规则
       */
      function initConfig() {
        if (!checkImportExcelTemplate()) {
          return;
        }
        // @ts-ignore
        startRow.value = props.sysImportExcelTemplate.startRow!;
        // 系统预设导入规则
        // @ts-ignore
        columns.value = props.sysImportExcelTemplate.detailList.map((item, index) => {
          return {
            title: `${index + 1}.${item.title}`,
            dataIndex: item.fieldName,
            require: item.dataRequired,
            width: 160,
          };
        });
        columns.value = [
          {
            title: '模版字段',
            dataIndex: 'importField',
            width: 100,
          },
          ...columns.value,
        ];

        if (props.importFile) {
          uploadExcelColumns();
        }

        let data: any = { importField: '导入字段' };
        props.sysImportExcelTemplate?.detailList?.map((item) => {
          data[item.fieldName!] = null;
        });
        dataSource.value = [data];
      }

      /**
       * 加载导入Excel数据
       */
      async function uploadExcelColumns() {
        importExcelColumns.value = await analysisExcel(props.importFile!);

        if (startRow.value > importExcelColumns.value.length) {
          message.warn('起始行大于Excel数据行数，请重新选择文件或更改起始行');
          return;
        }

        autoUpdateDataSource();
      }

      /**
       * 起始行改变
       */
      function handleStartRowChange() {
        autoUpdateDataSource();
      }

      /**
       * 根据用户设置起始行，自动匹配导入字段
       */
      function autoUpdateDataSource() {
        if (!checkImportExcelTemplate()) {
          return;
        }

        let data: any = { importField: '导入字段' };
        props.sysImportExcelTemplate?.detailList?.map((item) => {
          // 根据系统预设模版字段，到用户上传的Excel中自动匹配
          data[item.fieldName!] = matchSimilarColumn(item.title!);
        });
        dataSource.value = [data];
      }

      /**
       * 根据系统预设模版字段，到用户上传的Excel中自动匹配
       * 1、字段与Excel中字段完全一致
       * 2、字段与Excel中部分文字一致
       * @param title 系统预设模版字段
       */
      function matchSimilarColumn(title: string) {
        if (
          importExcelColumns.value.length === 0 ||
          importExcelColumns.value[startRow.value - 1].length === 0
        ) {
          return;
        }
        let similarColumn: number | null = null;
        // 1、字段与Excel中字段完全一致
        importExcelColumns.value[startRow.value - 1].forEach((item, index) => {
          if (item === title) {
            similarColumn = index;
            return;
          }
        });
        // 2、字段与Excel中部分文字一致
        if (similarColumn == null) {
          importExcelColumns.value[startRow.value - 1].forEach((item, index) => {
            if (
              title.toLowerCase().indexOf(item.toLocaleString()) > -1 ||
              item.toLowerCase().indexOf(title.toLocaleString()) > -1
            ) {
              similarColumn = index;
              return;
            }
          });
        }
        return similarColumn;
      }

      const columnOptions = computed(() => {
        if (
          importExcelColumns.value.length === 0 ||
          importExcelColumns.value[startRow.value - 1].length === 0
        ) {
          return;
        }
        return importExcelColumns.value[startRow.value - 1].map((item, index) => {
          return {
            value: index,
            label: `${index + 1}.${item}`,
          };
        });
      });

      async function handleStepNext() {
        nextBtnLoading.value = true;
        try {
          if (!checkImportExcelTemplate()) {
            return;
          }
          const importConfig: SysImportExcelTemplateDetailVO[] = [];
          // 1.必填验证
          for (let i = 0; i < props.sysImportExcelTemplate?.detailList?.length!; i++) {
            // @ts-ignore
            const detail = props.sysImportExcelTemplate?.detailList[i]!;
            if (detail?.dataRequired && dataSource.value[0][detail.fieldName] == null) {
              message.error(`请选择“${i + 1}.${detail?.title}”导入字段`);
              return;
            }
            importConfig.push({
              fieldName: detail.fieldName,
              index: dataSource.value[0][detail.fieldName],
            });
          }
          // 解析Excel
          const res = await analysis(
            props.sysImportExcelTemplate?.id as string,
            startRow.value,
            props.importFile!,
            importConfig,
          );
          if (res) {
            emit('next');
          }
        } catch (e) {
          console.error(e);
        } finally {
          nextBtnLoading.value = false;
        }
      }

      function checkImportExcelTemplate() {
        if (
          props.sysImportExcelTemplate?.detailList == null ||
          props.sysImportExcelTemplate?.detailList.length === 0
        ) {
          message.error('导入模版未配置，请联系管理员');
          return false;
        }
        return true;
      }

      return {
        startRow,
        columns,
        dataSource,
        nextBtnLoading,
        columnOptions,
        handleStepNext,
        handleStartRowChange,
      };
    },
  });
</script>

<style scoped lang="less">
  @import '../view.less';
</style>
